package cn.knightzz.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.knightzz.entity.SysUser;
import cn.knightzz.mapper.SysUserMapper;
import cn.knightzz.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.User;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author knightzz
 * @date 2021/4/9 13:52
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    SysUserMapper userMapper;

    @Resource
    SysUserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 判断用户名是否为空
        if (StrUtil.isEmpty(username)) {
            throw new RuntimeException("用户名不能为空");
        }
        // 如果用户名不为空 ,则从数据库中查询
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        // 查询对应的用户
        SysUser sysUser = userMapper.selectOne(queryWrapper);
        // 判断用户是否存在
        if (sysUser == null) {
            throw new UsernameNotFoundException(String.format("%s这个用户不存在", username));
        }
        // 如果用户存在则去查询用户的角色集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 根据用户名查询用户角色集合
        List<String> roleCodeList = userRoleService.getRoleCodeByUserName(username);
        // 封装角色信息
        roleCodeList.forEach(code -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(code);
            authorities.add(authority);
        });
        User user = new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
        return user;
    }
}
